<template>
  <div>
    <vol-box
      :model.sync="model"
      :padding="30"
      :title="title"
      :width="1000"
      :height="550"
    >
      <VolForm
        ref="myform"
        :loadKey="loadKey"
        :formFileds="formFileds"
        :formRules="formRules"
        :labelWidth="140"
      ></VolForm>

      <div slot="footer">
        <Button type="success" size="large" @click="addClick">保存</Button>
        <Button
          type="info"
          size="large"
          icon="md-close"
          @click="
            () => {
              this.model = false;
              this.$refs.myform.reset();
            }
          "
          >关闭</Button
        >
      </div>
    </vol-box>
    <vol-box
      :model.sync="model2"
      :padding="30"
      :title="(model2type == 14 ? '增加' : '减少') + '--授信额度'"
      :width="400"
      :height="150"
    >
      <VolForm
        ref="myform2"
        :loadKey="loadKey2"
        :formFileds="formFileds2"
        :formRules="formRules2"
        :labelWidth="100"
      ></VolForm>

      <div slot="footer">
        <Button type="success" size="large" @click="addClick2" v-loading="add2Load">保存</Button>
        <Button
          type="info"
          size="large"
          icon="md-close"
          @click=" model2 = false"
          >关闭</Button
        >
      </div>
    </vol-box>
  </div>
</template>
<script>
import VolForm from "@/components/basic/VolForm.vue";
export default {
  components: {
    VolBox: () => import("@/components/basic/VolBox.vue"),
    VolForm,
  },
  data() {
    return {
      isAlias: false, //应收帐户编号是否可用
      alias: "", //编辑储存账户编号
      loadKey: true,
      model: false,
      formFileds: {
        modifier: "", //修改人
        modifyDate: "", //修改时间（后端生成）
        modifyID: "", //修改人ID（拿不到）
        createDate: "", //创建时间（后端生成）
        createID: "", //创建人ID（拿不到）
        creator: "", //创建人
        is_delete: 0, //逻辑删除标志（后端要求必传）
        account_code_fk: "", //应收账户编号（后端生成）
        account_name: "", //应收账户名称
        is_entryaccount: 1, //是否入账
        is_credit: 0, //是否授信
        credit_total: '', //授信额度
        account_limit: "", //单笔挂账限额
        warn_phone: "", //警告手机
        warn_limit: "", //警告限额
        temporary_limit: "", //临时限额
        is_valid: 1, //是否有效
        is_autostop: 0, //是否自动停用
        date: [], //时间区间 （中专有效期）
        effec_enddate: "", //有效期，结束时间
        effec_startdate: "", //有效期，开始时间
        contact: "", //联系人
        contact_phone: "", //联系人电话
        finance_notes: "", //财务备注
        notes: "", //备注
        account_alias: "", //应收账户编号
        is_warn: 0, //是否警告（前端判断）
      },
      formRules: [
        // [{"title":"修改人","field":"modifier"},
        //            {"title":"修改时间","field":"modifyDate"},
        //            {"title":"修改人ID","field":"modifyID","type":"number"},
        //            {"title":"创建时间","field":"createDate"},
        //            {"title":"创建人ID","field":"createID","type":"number"},
        //            {"title":"创建人","field":"creator"},
        //            {"title":"逻辑删除标志","field":"is_delete","type":"number"},
        //            {"title":"应收账户编号","required":true,"field":"account_code_fk","disabled":true}],
        [
          {
            title: "应收账户名称",
            required: true,
            field: "account_name",
            type: "text",
            colSize: 4,
          },
          {
            title: "应收账户编号",
            required: true,
            field: "account_alias",
            type: "alphanumeric",
            colSize: 4,
            readonly: false,
            validator: (rule, val, callback) => {
              // console.log("kk", rule, val, callback);
              if (val) {
                let alphanumeric = /^\w+$/;
                // console.log(alphanumeric.test(val));
                if (!alphanumeric.test(val)) {
                  return "只能输入数字和字母！";
                }
                // this.http
                //   .post("/api/AccountsMain/CheckAlias", { alias: val }, true)
                //   .then((x) => {
                //     if (!x.status) {
                //       callback(new Error(this.sidMess));
                //     }
                //   });
              } else {
                return "只能输入数字和字母！";
              }
            },
          },
          // {
          //   colSize: 1,
          //   render: (h, { row, column, index }) => {
          //     return h("div", { style: {} }, [
          //       h(
          //         "a",
          //         {
          //           props: {},
          //           style: {
          //             "line-height": "32px",
          //             "font-size": "12px",
          //             "padding-left": "10px",
          //           },
          //           on: {
          //             click: (e) => {
          //               let alias = this.formFileds.account_alias;
          //               if (!alias) {
          //                 this.$message.error("请填写应收帐户编号！");
          //               } else {
          //                 // 去重接口
          //                 this.http
          //                   .post(
          //                     "/api/AccountsMain/CheckAlias",
          //                     { alias },
          //                     true
          //                   )
          //                   .then((x) => {
          //                     if (!x.status) {
          //                       this.isAlias = false;
          //                       this.$message.error("应收帐户编号重复！");
          //                       return;
          //                     } else {
          //                       this.isAlias = true;
          //                       this.$message.success("此编号可用！");
          //                     }
          //                   });
          //               }
          //             },
          //           },
          //         },
          //         "验证"
          //       ),
          //     ]);
          //   },
          // },
          {
            title: "是否有效",
            required: true,
            field: "is_valid",
            type: "switch",
            colSize: 4,
          },
        ],
        [
          {
            title: "联系人",
            required: true,
            field: "contact",
            type: "text",
            colSize: 4,
          },
          {
            title: "联系人电话",
            required: true,
            field: "contact_phone",
            type: "phone",
            colSize: 4,
          },
          {
            title: "有效期",
            range: true,
            required: true,
            field: "date",
            type: "date",
            colSize: 4,
          },
        ],
        // [
        //   // {
        //   //   title: "有效期终止",
        //   //   required: true,
        //   //   field: "effec_enddate",
        //   //   type: "date",
        //   // },
        // ],
        [
          {
            title: "是否授信",
            required: true,
            field: "is_credit",
            type: "switch",
            colSize: 4,
          },
          {
            title: "授信额度",
            // required: true,
            field: "credit_total",
            type: "decimal",
            // disabled: true,
            // readonly: true,
            colSize: 4,
            
          },
          {
            title: "是否允许入账",
            required: true,
            field: "is_entryaccount",
            type: "switch",
            colSize: 4,
          },
        ],
        [
          {
            title: "单笔限额",
            field: "account_limit",
            colSize: 4,
            type: "ZDecimal",
          },
          {
            title: "保留额度",
            field: "temporary_limit",
            colSize: 4,
            type: "ZDecimal",
          },
          {
            title: "是否自动停用",
            field: "is_autostop",
            type: "switch",
            colSize: 4,
          },
        ],
        [
          {
            title: "是否警告",
            required: true,
            field: "is_warn", //需修改
            type: "switch",
            colSize: 4,

            onChange: (value, option) => {
              // 关闭授信的话 禁止输入授信额度
              if (value == 0) {
                this.formRules.forEach((item) => {
                  item.forEach((ele) => {
                    if (ele.field == "warn_limit") {
                      ele.disabled = true;
                      this.formFileds.warn_limit = "";
                    }
                    if (ele.field == "warn_phone") {
                      ele.disabled = true;
                      this.formFileds.warn_phone = "";
                      console.log("kkkkkk", this.formFileds);
                    }
                    return;
                  });
                });
              } else {
                this.formRules.forEach((item) => {
                  item.forEach((ele) => {
                    ele.field == "warn_limit" ? (ele.disabled = false) : "";
                    ele.field == "warn_phone" ? (ele.disabled = false) : "";

                    return;
                  });
                });
              }
            },
          },
          {
            title: "警告限额",
            required: true,
            field: "warn_limit",
            type: "decimal",
            disabled: true,
            colSize: 4,
          },
          {
            title: "警告手机",
            required: true,
            field: "warn_phone",
            type: "phone",
            disabled: true,
            colSize: 4,
          },
        ],
        // [],

        // [
        //   {
        //     title: "财务备注",//去掉
        //     required: true,
        //     field: "finance_notes",
        //     colSize: 12,
        //     type: "textarea",
        //   },
        // ],
        [
          {
            title: "备注",
            required: true,
            field: "notes",
            colSize: 12,
            type: "textarea",
          },
        ],
      ],
      title: '',
      model2: false,
      loadKey2: true,
      formFileds2: {
        amount_total: '',
        notes: ''
      },
      formRules2: [
        [
          {
            title: "修改授信额度",
            field: "amount_total",
            type: "text",
            colSize: 12,
            required: true,
            validator: (rule, val) => {
              if (!/^[0-9]+(.[0-9]{1,2})?$/.test(val)) {
                return "授信额度为正数且小数只能为两位"
              }
              if (this.model2type == 14) {
                this.credit_status = true
              } else {
                let num = Number(this.formFileds.credit_total) - Number(val)
                if (num < 0) {
                  this.$message.error("授信额度不能为负数");
                  this.credit_status = false
                } else {
                  this.credit_status = true
                }
              }
            },
          },
          {
            title: "备注",
            field: "notes",
            type: "textarea",
            colSize: 12,
          }
        ]
      ],
      credit_status: false,
      model2type: 14,
      add2Load: false,
    };
  },
  watch: {
    'formFileds.is_credit': {
      handler(n,o){
        let credit_total = this.getFormOption('credit_total')
        if (this.title == '应收帐户--新建') {
          credit_total.readonly = false
          if (n == 0) {
            this.formFileds.credit_total = '--'
            credit_total.disabled = true
          } else {
            credit_total.disabled = false
            this.formFileds.credit_total = ''
          }
        } else {
          credit_total.disabled = false
          credit_total.readonly = true
          if (n == 0) {
            this.formRules.forEach((item) => {
              item.forEach((ele) => {
                if ( ele.field == "credit_total") {
                  ele.extra =  {}
                }
                return;
              });
            });
          } else {
            this.formRules.forEach((item) => {
              item.forEach((ele) => {
                if ( ele.field == "credit_total") {
                  ele.extra =  {
                      render: (h) => {
                      return h(
                        "div",
                        {
                          props: {},
                          style: { color: "#03A9F4", cursor: "pointer" },
                        },
                        [
                          h(
                            "span",
                            {
                              style: {},
                              on: {  click: () => {
                                this.$refs.myform2.reset()
                                this.model2type = 14
                                this.formFileds2.amount_total = ''
                                this.formFileds2.notes = ''
                                this.model2 = true
                              } },
                            },'增加'
                          ),
                          h(
                            "span",
                            {
                              style: {
                                marginLeft: '10px'
                              },
                              on: {  click: () => {
                                this.$refs.myform2.reset()
                                this.model2type = 15
                                this.formFileds2.amount_total = ''
                                this.formFileds2.notes = ''
                                this.model2 = true
                              } },
                            },'减少'
                          ),
                        ]
                      );
                    },
                  }
                }
                return;
              });
            });
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    getFormOption (field) {
      let option;
      this.formRules.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        })
      })
      return option;
    },
    open(e) {
      this.title = e == 0 ? '应收帐户--新建' : '应收帐户--编辑'
      this.formReset();
      this.model = true;
      let credit_total = this.getFormOption('credit_total')
      if (e == 0) {
        this.formRules[0][1].readonly = false
        this.formRules[0][1].required = true
        credit_total.readonly = false
        credit_total.disabled = true
        credit_total.extra =  {}
      } else {
        this.formRules[0][1].readonly = true
        this.formRules[0][1].required = false
        credit_total.readonly = true
        credit_total.disabled = false
      }
    },
    // 清空表单
    formReset() {
      this.$refs.myform.reset();
    },
    // 新建保存按钮
    addClick() {
      // console.log("新建保存");

      this.$refs.myform.validate(() => {
        let time = this.formFileds.date;
        if (time.length == 2) {
          this.formFileds.effec_startdate = time[0];
          this.formFileds.effec_enddate = time[1];
        } else {
          this.$message.error("请选择正确的有效区间！");
          return;
        }
        // if (this.formFileds.account_alias == this.alias) {
        // } else if (!this.isAlias) {
        //   this.$message.error("请先验证账户编号是否重复！");
        //   return;
        // }
        // 新建接口
        this.http
          .post("/api/AccountsMain/AccountsSet", this.formFileds, true)
          .then((x) => {
            if (!x.status) return this.$message.error(x.message);
            this.$message.success("操作成功");
            this.$parent.refreshClick();
            this.model = false;
            this.isAlias = false;
            this.formReset();
            // let data = { startingTime: new Date() };
            // this.$refs.myform.reset(data);
            // this.refresh();
          });
      });
    },

    addClick2 () {
      this.$refs.myform2.validate((valid) => {
        if (this.credit_status) {
          this.add2Load = true
          let params = {
            account_alias: this.formFileds.account_alias,
            account_code: this.formFileds.account_code_fk,
            account_name: this.formFileds.account_name,
            business_date: new Date(),
            creator: JSON.parse(sessionStorage.getItem('user')).userName,
            customer_name: '',
            customer_phone: '',
            is_valid: this.formFileds.is_valid,
            out_order_id: '',
            payment_method: '现金',
            type_func: this.model2type,
            type_record: 3,
            verify_status: 1,
            ...this.formFileds2
          }
          this.http.post('api/AccountsDetail/AccountsDetailSet', params).then(res => {
            this.add2Load = false
            if (res.status) {
              this.model2 = false;
              this.$parent.AccountsGet()
              if (this.model2type == 14) {
                this.formFileds.credit_total = Number(this.formFileds.credit_total) + Number(this.formFileds2.amount_total)
              } else {
                this.formFileds.credit_total = Number(this.formFileds.credit_total) - Number(this.formFileds2.amount_total)
              }
              this.$message.success('授信成功');
            } else {
              this.$message.error(res.message);
            }
          })
        }
      })
    },
    checkAlias(alias) {
      // 去重接口;
      this.http
        .post("/api/AccountsMain/CheckAlias", { alias }, true)
        .then((x) => {
          if (!x.status) {
            this.isAlias = false;
            this.$message.error("应收帐户编号重复！");
            return;
          } else {
            this.isAlias = true;
            this.$message.success("此编号可用！");
          }
        });
    },
    // 选中表格数据
    getRows(rows) {
      this.rows = rows;
      console.log("选中数据", rows);
    },
    reset() {},
  },
};
</script>
<style lang="less" scoped>
h3 {
  font-weight: 500;
  > span:last-child {
    margin-left: 30px;
  }
}
</style>